package com.example.roomwordsample

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.lifecycleScope
import com.example.roomwordsample.dao.WordRoomDatabase
import com.example.roomwordsample.model.Word
import com.example.roomwordsample.repository.WordRepository
import com.example.roomwordsample.ui.screen.HomeScreen
import com.example.roomwordsample.ui.theme.RoomWordSampleTheme
import com.example.roomwordsample.viewmodel.WordViewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val wordDao = WordRoomDatabase.getDatabase(application, lifecycleScope).wordDao()
        val viewModel: WordViewModel by viewModels {
            WordViewModel.WordViewModelFactory(
                WordRepository(wordDao)
            )
        }
        setContent {
            RoomWordSampleTheme {
                ApplicationStart(viewModel, this)
            }
        }
    }
}

@Composable
fun ApplicationStart(viewModel: WordViewModel, activity: ComponentActivity) {

    var words by mutableStateOf(listOf<Word>())

    viewModel.items.observe(activity, {
        words = words + it
    })

    HomeScreen(
        words = words,
        onAddItemChange = {
            val word = Word(0, it)
            viewModel.insert(word = word)

        },
        onDeleteChange = {
            viewModel.delete(it)
        }
    )

}
